import router from '@/router'
import store from '@/store'
import {MessageBox} from 'mint-ui';
import {
    getToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

// const whiteList = ['/login', '/register']; // 白名单列表

router.beforeEach(async (to, from, next) => {
    // 设置页面标题
    document.title = getPageTitle(to.meta.title);

    // determine whether the user has logged in判断用户是否已经登录（先得到token）
    const hasToken = getToken();

    if (hasToken) {
        if (to.path === '/login') { //已经登录（得到token存在）
            // 已经登录，跳转到首页
            next({
                path: '/'
            })
        } else {
            //获取用户信息
            const hasGetUserInfo = store.getters.userData && store.getters.userData.name
            if (hasGetUserInfo) {
                next()
            } else {
                try {
                    console.log('重新登录，获取用户数据');
                    store.commit('user/LOGOUT');
                    MessageBox('Notice', 'login in again');
                    // get user info
                    // await store.dispatch('user/getInfo');
                    next('/login')
                } catch (error) {
                    // 清除用户信息，退出登录，跳转登录页
                    store.commit('user/LOGOUT');
                    MessageBox('Notice', error || 'Has Error');
                    // next(`/login?redirect=${to.path}`)
                    next('/login')
                }
            }
        }
    } else {
        /* has no token */
        // if (whiteList.indexOf(to.path) !== -1) {
        //     // 白名单中，无需验证
        //     next()
        // } else {
        //     // other pages that do not have permission to access are redirected to the login page.
        //     next(`/login?redirect=${to.path}`)
        // }
        // next({path: '/login'})
        if (to.path == '/login') {
            next();
        }
        else if (to.path == '/register') {
            next();
        } 
        else {
            next({
                replace: true,
                path: '/login'
            })
        }

    }
});